#include "mainwindow.h"
#include "ui_mainwindow.h"

#include<QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ws = new QWebSocket();

    // 连接ws 相关的处理函数
    connect(ws,SIGNAL(disconnected),this,SLOT(on_ws_disconnect));
    //  connect(ws,SIGNAL(textMessageReceived(QString)),this,SLOT(on_ws_receiver(QString)));
    connect(ws,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(on_ws_error(QAbstractSocket::SocketError)));
    // 接收消息的处理
    connect(ws,QWebSocket::textMessageReceived,[this](QString message ){
        qDebug()<<"get message "<<message;
        auto text = ui->plainTextEdit->toPlainText();
        text  +="\n"+message;
        ui->plainTextEdit->setPlainText(text);
    });
}

MainWindow::~MainWindow()
{
    if (ws != nullptr){
        delete ws;
    }
    delete ui;
}

void MainWindow::on_ws_disconnect(){
    ws = nullptr ;
}

void MainWindow::on_ws_error(QAbstractSocket::SocketError err )
{
    qDebug()<<"error "<<err;
}

void MainWindow::on_ws_receiver(QString message)
{
    qDebug()<<"message"<<message;

    auto text = ui->plainTextEdit->toPlainText();
    text  +="\n"+message;
    ui->plainTextEdit->setPlainText(text);
}

// ws 连接
void MainWindow::on_btn_connect_clicked()
{
    if (ws == nullptr){
        ws = new QWebSocket();
    }
    ws->open(QUrl(ui->et_ws_url->text()));
    qDebug()<<"....";
}

// 发送消息的响应函数
void MainWindow::on_btn_send_clicked()
{
    // 获取到输入框的文本信息
    auto str =  ui->et_content->text();
    qDebug()<<"send .... "<<str ;
    if (ws != nullptr){
        ws->sendTextMessage(str);
    }

    // 清空文本输入框
    ui->et_content->setText("");
}
